/**
 * @file mem.c
 * @author etcfly (etcflywy@126.com)
 * @brief 
 * @version 1.0.0
 * @date 2025-11-10
 * 
 * @copyright Copyright (c) 2025
 * 
 */
#include "mem.h"
#include <unistd.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>

// 32位系统的备选地址列表（按优先级排序）
static const unsigned long load_addresses_32bit[] = {
    0x08000000,     // 128MB - 主要选择
    0x04000000,     // 64MB - 备用选择  
    0x10000000,     // 256MB - 第三个选择
    0x20000000,     // 512MB - 高地址选择
    0x0800000,      // 8MB - 低地址备选
    0 // 哨兵值
};


void* allocate_elf_memory_32bit(size_t size) 
{
    const unsigned long *addr_ptr = load_addresses_32bit;
    
    while (*addr_ptr) {
        void* result = mmap((void*)*addr_ptr, size,
                           PROT_READ | PROT_WRITE | PROT_EXEC,
                           MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
                           -1, 0);
        
        if (result != MAP_FAILED) {
            printf("Allocated at: 0x%lx\n", *addr_ptr);
            return result;
        }
        
        printf("Address 0x%lx busy, trying next...\n", *addr_ptr);
        addr_ptr++;
    }
    
    // // 所有指定地址都失败，让系统选择
    printf("All specified addresses busy, using system choice\n");
    // return mmap(NULL, size, PROT_READ | PROT_WRITE | PROT_EXEC,
    //             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    return NULL;
}